package com.xiongjie;

import org.infinispan.Cache;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.eviction.EvictionStrategy;
import org.infinispan.manager.DefaultCacheManager;
import org.infinispan.manager.EmbeddedCacheManager;
import java.io.IOException;

/**
 * 内嵌缓存的使用
 */
public class Application {

    /**
     * 每次只能有一个DefaultCacheManager进行获取来进行操作
     * @param args
     */
    public static void main(String[] args) {
//        defaultCacheManager();
//        defaultCacheManagerByXml();
//        defaultCacheManagerByCustom();
        embeddedCache();
    }

    /**
     * 1.使用DefaultCacheManager缓存
     */
    public static void defaultCacheManager(){
        System.out.println("调用方法：defaultCacheManager");

        //两个缓存的对象是一致的，默认的缓存名字就是___defaultcache,不能同时获取
        Cache<Object, Object> cache1=new DefaultCacheManager().getCache();
//        Cache<Object, Object> cache2=new DefaultCacheManager().getCache("___defaultcache");

        //以下是常用的缓存的方法
        cache1.put(1,1);
        System.out.println(cache1.values());

        System.out.println(cache1.get(1));

        cache1.remove(1);
        System.out.println(cache1.values());

        System.out.println(cache1.isEmpty());

        cache1.putIfAbsent(2,2);
        System.out.println(cache1.values());

        System.out.println(cache1.containsKey(2));
    }

    /**
     * 2.使用DefaultCacheManager缓存
     * 使用infinispan.xml文件来加载缓存配置
     */
    public static void defaultCacheManagerByXml(){
        System.out.println("调用方法：defaultCacheManagerByXml");

        try {
            Cache<Object, Object> cache = new DefaultCacheManager("infinispan.xml").getCache("xml-configured-cache");

            cache.put(3,3);
            System.out.println(cache.values());

        } catch (IOException e) {
            System.out.println("infinispan.xml文件没找到");
        }
    }

    /**
     * 3.使用DefaultCacheManager缓存
     * 使用代码自定义缓存配置
     */
    public static void defaultCacheManagerByCustom(){
        System.out.println("调用方法：defaultCacheManagerByCustom");

        DefaultCacheManager manager=new DefaultCacheManager();
        Configuration configuration=new ConfigurationBuilder()
                .eviction()
                .strategy(EvictionStrategy.LRU)
                .maxEntries(10)
                .build();
        manager.defineConfiguration("custom-cache",configuration);

        Cache<Object,Object> cache=manager.getCache("custom-cache");
        cache.put(4,4);
        System.out.println(cache.values());
    }

    /**
     * 4.使用embeddedCache缓存，它是DefaultCacheManager实现的接口
     */
    public static void embeddedCache(){
        System.out.println("调用方法：embeddedCache");

        EmbeddedCacheManager embeddedCacheManager=new DefaultCacheManager();
        Cache<Object,Object> cache = embeddedCacheManager.getCache();

        cache.put(5,5);
        System.out.println(cache.values());
    }
}